const express = require('express')
const app = express()
app.listen(3000, () => {
    console.log('3000端口开启了，可以访问: http://localhost:3000')
})
let qs = require('querystring')
const fs = require('fs')
const path = require('path')
const { static } = require('express')
//开放静态资源
app.use('/static', express.static('static'))

//开启接收post的中间件
app.use(express.urlencoded({ extended: false }))



//加载登录注册的界面
app.get('/login', (req, res) => {
    let filepath = path.join(__dirname, '/views/login.html')
    res.sendFile(filepath)
})
app.get('/register', (req, res) => {
    let filepath = path.join(__dirname, '/views/register.html')
    res.sendFile(filepath)
})

app.use((req, res, next) => {
    let d = new Date()
    let year = d.getFullYear()
    let month = d.getMonth() + 1
    let day = d.getDate()
    let h = d.getHours()
    let m = d.getMinutes()
    let s = d.getSeconds()

    if (month < 10) {
        month = '0' + month
    }
    if (day < 10) {
        day = '0' + day
    }
    if (h < 10) {
        h = '0' + h
    }
    if (m < 10) {
        m = '0' + m
    }
    if (s < 10) {
        s = '0' + s
    }

    //我们应该把中间件公共的数据放到req上。因为每个路由的req对象都是同一个
    req.time = ` ${year}年${month}月${day}日 ${h}:${m}:${s}`

    console.log(req.time);
    next() //去找最终的匹配路由
})


//登录判断
app.post('/dologin', (req, res) => {
    let result = fs.readFileSync('./persons.json', { encoding: 'utf-8' })
    result = JSON.parse(result);


    let userwho = result.findIndex(item => item.username === req.body.tel && item.password === req.body.pass)


    if (userwho === -1) {
        res.send('用户名或密码错误')
        return
    }
    res.send('登陆成功')
})



//注册判断
app.post('/doregister', (req, res) => {
    let result = fs.readFileSync('./persons.json', { encoding: 'utf-8' })
    result = JSON.parse(result);



    let username = req.body.tel
    let password = req.body.pass
    let time = req.time

    //验证数据是否正确
    if (!username) {
        res.send('用户名不能为空')
        return
    }
    if (!password) {
        res.send('密码不能为空')
        return
    }
    if (password !== req.body.pass2) {
        res.send('两次密码输入不一致')
        return
    }





    let newUser = { username, password, time }//用户注册的信息

    console.log(newUser);

    let userwho = result.findIndex(item => item.username === username)


    if (userwho !== -1) {
        res.send('用户名已占用')
        return
    } else {
        let persons = fs.readFileSync('persons.json', 'utf8')
        // console.log(persons);  //这是string,得转换
        persons = JSON.parse(persons)//json字符串转换成对象

        persons.push(newUser)//添加

        persons = JSON.stringify(persons)//添加完再转成json字符串
        fs.writeFileSync('persons.json', persons)//写入

        res.send('注册成功')
        return
    }

})